//
//  SKRegisterNextVController.m
//  SKaURobot
//
//  Created by cdong on 16/2/18.
//  Copyright © 2016年 cdong. All rights reserved.
//

#import "SKRegisterNextVController.h"
#import "SKRegisterNextView.h"
#import "AFHTTPSessionManager.h"
#import "SKFirstVController.h"

@interface SKRegisterNextVController ()<UITextFieldDelegate>

@property (nonatomic ,strong)SKRegisterNextView *registerNextView;
@property (nonatomic ,assign)NSInteger pwdShiftFlag;
@property (nonatomic ,assign)NSInteger pwdShiftFlagNext;

@end

@implementation SKRegisterNextVController

- (void)loadView{
    self.registerNextView = [[SKRegisterNextView alloc]initWithFrame:[[UIScreen mainScreen]bounds]];
    self.view = self.registerNextView;
}

- (UIStatusBarStyle)preferredStatusBarStyle{
    return UIStatusBarStyleLightContent;
}

- (void)backBtnAction:(UIButton *)sender{
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [RGBColorEncapsulation colorWithRGB:0xf4f4f4 alpha:1];
    [self.registerNextView.backBtn addTarget:self action:@selector(backBtnAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.registerNextView.registerNextBtn addTarget:self action:@selector(registerNextBtnAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.registerNextView.pawBtn addTarget:self action:@selector(pwdShiftBtnAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.registerNextView.pawNextBtn addTarget:self action:@selector(pwdShiftBtnActionNext:) forControlEvents:UIControlEventTouchUpInside];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textFieldChanged) name:UITextFieldTextDidChangeNotification object:self.registerNextView.userNameTF];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textFieldChanged) name:UITextFieldTextDidChangeNotification object:self.registerNextView.pawTF];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textFieldChanged) name:UITextFieldTextDidChangeNotification object:self.registerNextView.pawNextTF];
    self.pwdShiftFlag = 0;
    self.pwdShiftFlagNext = 0;
    self.registerNextView.userNameTF.delegate = self;
    self.registerNextView.pawNextTF.delegate = self;
    self.registerNextView.pawTF.delegate = self;
}

// 输入框文字判断
- (void)textFieldChanged{
    if (![self.registerNextView.userNameTF.text isEqualToString:@""] && ![self.registerNextView.pawTF.text isEqualToString:@""] && ![self.registerNextView.pawNextTF.text isEqualToString:@""]) {
        self.registerNextView.registerNextBtn.userInteractionEnabled = YES;
        [self.registerNextView.registerNextBtn setTitleColor:[RGBColorEncapsulation colorWithRGB:0xffffff alpha:1] forState:UIControlStateNormal];
    }else{
        self.registerNextView.registerNextBtn.userInteractionEnabled = NO;
        [self.registerNextView.registerNextBtn setTitleColor:[RGBColorEncapsulation colorWithRGB:0xffffff alpha:.5] forState:UIControlStateNormal];
    }
}

// 切换密文／明文
- (void)pwdShiftBtnAction:(UIButton *)sender{
    if (self.pwdShiftFlag == 1) {
        self.registerNextView.pawTF.secureTextEntry = YES;
        [self.registerNextView.pawBtn setBackgroundImage:[UIImage imageNamed:@"icon_eye"] forState:UIControlStateNormal];
        self.pwdShiftFlag = 0;
    }else{
        self.registerNextView.pawTF.secureTextEntry = NO;
        [self.registerNextView.pawBtn setBackgroundImage:[UIImage imageNamed:@"icon_eye_red"] forState:UIControlStateNormal];
        self.pwdShiftFlag = 1;
    }
}

// 切换密文／明文Next
- (void)pwdShiftBtnActionNext:(UIButton *)sender{
    if (self.pwdShiftFlagNext == 1) {
        self.registerNextView.pawNextTF.secureTextEntry = YES;
        [self.registerNextView.pawNextBtn setBackgroundImage:[UIImage imageNamed:@"icon_eye"] forState:UIControlStateNormal];
        self.pwdShiftFlagNext = 0;
    }else{
        self.registerNextView.pawNextTF.secureTextEntry = NO;
        [self.registerNextView.pawNextBtn setBackgroundImage:[UIImage imageNamed:@"icon_eye_red"] forState:UIControlStateNormal];
        self.pwdShiftFlagNext = 1;
    }
}

// 确定（注册）
- (void)registerNextBtnAction:(UIButton *)sender{
    
    if ([self.registerNextView.pawTF.text isEqualToString:@""] || [self.registerNextView.pawNextTF.text isEqualToString:@""] || [self.registerNextView.userNameTF.text isEqualToString:@""]) {
        [self alertReminderMessage:@"昵称或密码不能为空"];
        return;
    }
    
    if (![self.registerNextView.pawTF.text isEqualToString:self.registerNextView.pawNextTF.text]) {
        [self alertReminderMessage:@"两次输入的密码不一致"];
        return;
    }
    
    NSString* userNameRegex = @"[a-zA-Z\u4e00-\u9fa5][a-zA-Z0-9\u4e00-\u9fa5]+";
    NSPredicate* userNameTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",userNameRegex];
    BOOL isMatchName = [userNameTest evaluateWithObject:self.registerNextView.userNameTF.text];
    if (!isMatchName) {
        [self alertReminderMessage:@"昵称只能由文字、数字和字母组成"];
        return;
    }
    
    NSString* pwdRegex = @"^[A-Za-z0-9]{6,16}$";
    NSPredicate* pwdTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",pwdRegex];
    BOOL isMatch = [pwdTest evaluateWithObject:self.registerNextView.pawTF.text];
    if (!isMatch) {
        [self alertReminderMessage:@"密码只能有数字和字母组成,6~16位"];
        return;
    }
    
    // http://api.au-smart.cn/index.php?act=register&userName=pengpeng&mobile=13588827231&password=123456
    NSUserDefaults *defualts = [NSUserDefaults standardUserDefaults];
    NSString *mobile = [defualts objectForKey:@"mobile"];
    NSString *urlStr =  [NSString stringWithFormat:@"http://api.au-smart.cn/index.php?act=register&userName=%@&mobile=%@&password=%@",self.registerNextView.userNameTF.text,mobile,self.registerNextView.pawTF.text];
    NSString *utf = [urlStr stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    [manager POST:utf parameters:nil progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSNumber *error = [responseObject objectForKey:@"error"];
        NSNumber *uid = [responseObject objectForKey:@"uid"];
        NSString *sesskey = [responseObject objectForKey:@"sesskey"];
        NSNumber *errorCode = [responseObject objectForKey:@"errorCode"];
        if (error.integerValue == 0) {
            [defualts setObject:self.registerNextView.userNameTF.text forKey:@"userName"];
            [defualts setObject:self.registerNextView.pawTF.text forKey:@"password"];
            [defualts setObject:uid forKey:@"uid"];
            [defualts setObject:sesskey forKey:@"sesskey"];
            SKFirstVController *firstVController = [[SKFirstVController alloc]init];
            [self.navigationController pushViewController:firstVController animated:YES];
        }else{
            if (errorCode.integerValue == 1004) {
                [self alertReminderMessage:@"用户名已经被注册"];
            }
            if (errorCode.integerValue == 1009) {
                [self alertReminderMessage:@"注册失败"];
            }
            if (errorCode.integerValue == 1005) {
                [self alertReminderMessage:@"用户名长度不能少于3个字符"];
            }
            if (errorCode.integerValue == 1006) {
                [self alertReminderMessage:@"用户名长度不能多于16个字符"];
            }else{
                [self alertReminderMessage:@"注册失败"];
            }
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
    }];
}

// 提示弹框
- (void)alertReminderMessage:(NSString *)message
{
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:message message:@"" preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"好的" style:UIAlertActionStyleDefault handler:nil];
    [alertController addAction:okAction];
    [self presentViewController:alertController animated:YES completion:nil];
}

// 点击return回收键盘
- (BOOL)textFieldShouldReturn:(UITextField *)textField{
    [textField resignFirstResponder];
    return YES;
}

// 点击空白回收键盘
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    [self.registerNextView.userNameTF resignFirstResponder];
    [self.registerNextView.pawTF resignFirstResponder];
    [self.registerNextView.pawNextTF resignFirstResponder];
}

-(void)dealloc{
    
    [[NSNotificationCenter defaultCenter]removeObserver:self];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
